define(['app'], function(app) {
    app.controller('uploadFile', function($uibModalInstance, $timeout, Upload, _context, _dialog) {
        var self = this;

        self.init = function() {
            self.name = '';
            self.completed = false;
        }

        var modalInstances = [];
        self.upload = function(file) {
            self.name = '';
            self.completed = false;
            if (file != null) {
                //self.name = file.name;
                // upload file
                Upload.upload({
                    url: '/note/data/upload',
                    method: 'POST',
                    data: {
                        'filepath': _context.path,
                        'filename': file.name,
                        'file': file
                    },
                    timeout: 600000
                }).then(function(response) {
                    if (response.status == 200) {
                        self.name = file.name;
                    }
                    self.completed = true;
                    while (modalInstances.length > 0) {
                        modalInstances.shift().close();
                    }
                });
                // show upload processing
                setTimeout(function() {
                    if (!self.completed) {
                        _dialog.modal({
                            size: 'sm',
                            windowClass: 'upload-modal',
                            template: '<div class="modal-body">' +
                                      '  <p>正在加速上传文件，请稍候...</p>' +
                                      '</div>',
                            controller: ['$uibModalInstance', function(_uibModalInstance) {
                                if (self.completed) {
                                    $timeout(function() {
                                        while (modalInstances.length > 0) {
                                            modalInstances.shift().close();
                                        }
                                    }, 300);
                                } else {
                                    modalInstances.push(_uibModalInstance);
                                    $timeout(function() {
                                        $('.upload-modal>.modal-dialog').css('margin-top', '120px');
                                    });
                                }
                            }]
                        });
                    }
                }, 250);
            }
        }

        self.insert = function(valid) {
            if (valid) {
                $uibModalInstance.close({ name: self.name });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
